<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <k-form-build
      :value="jsonData"
      @submit="handleSubmit"
      ref="kFormBuild"/>
  </a-modal>
</template>

<script>
import { FormMixin } from '@/mixins/FormMixin'
import { getObjByCode } from '@/api/dynamicForm/design'
import { getObj, addObj, putObj } from '@/api/dynamicForm/data'
export default {
  name: 'AddOrUpdate',
  mixins: [FormMixin],
  data () {
    return {
      jsonData: {},
      id: '',
      confirmLoading: false,
      formData: {
        version: '',
        code: ''
      }
    }
  },
  methods: {
    edit (id, type, code) {
      this.id = id
      this.visible = true
      getObjByCode(code).then(res => {
        this.formData.version = res.data.version
        this.formData.code = res.data.code
        this.jsonData = JSON.parse(res.data.jsonData)
      })
      this.$nextTick(() => {
        const { form: { setFieldsValue, resetFields } } = this.$refs.kFormBuild
        if (['edit', 'show'].includes(type)) {
          this.confirmLoading = true
          getObj(id).then(res => {
            const record = JSON.parse(res.data.data)
            this.confirmLoading = false
            this.$nextTick(() => {
              setFieldsValue(record)
            })
          })
        } else {
          resetFields()
        }
      })
    },
    handleSubmit () {
      this.$refs.kFormBuild.getData().then(async res => {
        this.confirmLoading = true
        // 获取数据成功
        try {
          if (this.type === 'add') {
            await addObj({
              ...this.formData,
              data: JSON.stringify(res)
            })
          } else if (this.type === 'edit') {
            await putObj({
              id: this.id,
              ...this.formData,
              data: JSON.stringify(res)
            })
          }
          setTimeout(() => {
            this.confirmLoading = false
            this.$emit('ok')
            this.visible = false
          }, 1500)
        } catch (e) {
          this.$message.error(e.msg)
          this.confirmLoading = false
        }
      }).catch(err => {
      })
    }
  }
}
</script>

<style scoped>

</style>
